package com.estrend.redbird.utils

import java.security.Key
import java.util.Base64
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.spec.SecretKeySpec

object  AesUtils {
    private const val ALGORITHM = "AES"
    private const val TRANSFORMATION = "AES"

    fun generateKey(): String {
        val keyGen = KeyGenerator.getInstance(ALGORITHM)
        keyGen.init(128)
        val secretKey = keyGen.generateKey()
        return Base64.getEncoder().encodeToString(secretKey.encoded)
    }


    fun encrypt(data: ByteArray, key: String): ByteArray {
        val secretKey = decodeKey(key)
        val cipher = Cipher.getInstance(TRANSFORMATION)
        cipher.init(Cipher.ENCRYPT_MODE, secretKey)
        return cipher.doFinal(data)
    }


    fun decrypt(data: ByteArray, key: String): ByteArray {
        val secretKey = decodeKey(key)
        val cipher = Cipher.getInstance(TRANSFORMATION)
        cipher.init(Cipher.DECRYPT_MODE, secretKey)
        return cipher.doFinal(data)
    }


    private fun decodeKey(key: String): Key {
        val decodedKey = Base64.getDecoder().decode(key)
        return SecretKeySpec(decodedKey, 0, decodedKey.size, ALGORITHM)
    }

}